<template>
  <a-card>
    <template #title>
      <a-form layout="vertical">
        <a-row :gutter="24">
          <a-col :md="6" :xs="24" v-permiss="['select-merchant']">
            <a-form-item :label="$t('商户名称')">
              <a-select v-model:value="page.mchId" allowClear>
                <a-select-option v-for="item in merchantList" :key="item.mchId" :value="item.mchId">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24" v-permiss="['select-merchant']">
            <a-form-item :label="$t('交易流水')">
              <a-input v-model:value="page.transactionId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('平台订单号')">
              <a-input v-model:value="page.platOrderId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('商户订单号')">
              <a-input v-model:value="page.orderId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('应用ID')">
              <a-input v-model:value="page.appId"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('客户姓名')">
              <a-input v-model:value="page.userName"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('身份证号码')">
              <a-input v-model:value="page.idCard"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('收款账号')">
              <a-input v-model:value="page.bankNo"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('标识符')">
              <a-input v-model:value="page.identifier"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item label="cci">
              <a-input v-model:value="page.cci"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('标识符')">
              <a-input v-model:value="page.identifier"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('APP名称')" >
              <a-select v-model:value="page.productName" allowClear>
                <a-select-option v-for="item in productNameList" :key="item" :value="item">{{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('打款操作人')" >
              <a-select v-model:value="page.operatorName" allowClear>
                <a-select-option v-for="item in operationList" :key="item" :value="item">{{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('完成时间')">
              <a-range-picker style="width: 100%" v-model:value="page.resolveTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('创建时间')">
              <a-range-picker style="width: 100%" v-model:value="page.createTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('完成时间')">
              <a-range-picker style="width: 100%" v-model:value="page.resolveTime" valueFormat="YYYY-MM-DD"
                              format="YYYY-MM-DD"/>
            </a-form-item>
          </a-col>


        </a-row>
        <a-row :gutter="24">
          <a-col :span="24" style="text-align: right">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <a-button :loading="exportLoading" @click="exportExcel" v-permiss="['export']">{{ $t('导出') }}</a-button>
      <a-button :loading="exportPaymentLoading" type="primary" style="margin-left: 10px" @click="exportPayment"
                v-permiss="['exportPayment']">
        <ExportOutlined/>
        {{ $t('导出打款') }}
      </a-button>
      <a-button :loading="exportLoading" type="primary" style="margin-left: 10px" @click="importPayment"
                v-permiss="['importPayment']">
        <ImportOutlined/>
        {{ $t('导入回执') }}
      </a-button>
      <a-button type="primary" style="margin-left: 10px" @click="batchPush" v-permiss="['batch-push']">{{
          $t('批量推送')
        }}
      </a-button>
    </div>
    <a-table row-key="platOrderId" :loading="tableLoading" :data-source="tableData" :columns="tableColumn"
             :row-selection="rowSelection"
             :scroll="{x:true,y:600}"
             :pagination="pagination">
      <template #handle="{record}">
        <a-button v-if="record.status !== 0 && record.status !== 1" type="link" @click="push(record)"
                  v-permiss="['push']">{{
            $t('推送')
          }}
        </a-button>
        <a-button v-show="record.status === 2" type="link" v-permiss="['voucher']" @click="lookVoucher(record)">
          {{ $t('凭证') }}
        </a-button>
        <a-button v-if="record.status === 0 || record.status === 1" type="link"
                  @click="statusVisible = true,statusForm = {...record,changeStatus:1}" v-permiss="['status']">
          {{ $t('变更状态') }}
        </a-button>
      </template>
    </a-table>
    <a-modal v-model:visible="statusVisible" :title="$t('变更状态')" @ok="changeStatusConfirm">
      <a-form :model="statusForm">
        <a-form-item :label="$t('平台订单号')">
          {{ statusForm.platOrderId }}
        </a-form-item>
        <a-form-item :label="$t('客户姓名')">
          {{ statusForm.userName }}
        </a-form-item>
        <a-form-item :label="$t('银行名称')">
          {{ statusForm.bankName }}
        </a-form-item>
        <a-form-item :label="$t('收款账号')">
          {{ statusForm.bankNo }}
        </a-form-item>
        <a-form-item :label="$t('变更状态')">
          <a-radio-group v-model:value="statusForm.changeStatus">
            <a-radio :value="1">{{ $t('打款成功') }}</a-radio>
            <a-radio :value="2">{{ $t('打款失败') }}</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
    <!--    查看凭证-->
    <a-modal v-model:visible="voucherVisible" width="1200px" :footer="false">
      <div style="padding:15px">
        <iframe :src="voucherUrl" frameborder="0" style="height:920px;width:100%"></iframe>
      </div>
    </a-modal>
    <!--    导入回执-->
    <a-modal v-model:visible="importPaymentVisible" :title="$t('导入回执')" @cancel="importClose"
             @ok="importPaymentConfirm">
      <a-form :model="importForm" ref="importRefForm" :label-col="{span:5}">
        <a-form-item :label="$t('数据所属商户')" name="mchId"
                     :rules="{required:true,message:$t('请选择'),trigger: 'change',type: 'number'}">
          <a-select v-model:value="importForm.mchId" allowClear @change="importChangeProductName">
            <a-select-option v-for="item in merchantList" :key="item.mchId" :value="item.mchId">{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('数据所属APP')" name="productName"
                     :rules="{required:true,message:$t('请选择'),trigger: 'change'}">
          <a-select v-model:value="importForm.productName" allowClear>
            <a-select-option v-for="item in importProductList" :key="item" :value="item">{{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="$t('上传文件')" name="file"
                     :rules="{required:true,type:'array',message:$t('请选择'),trigger: 'change'}">
          <a-upload
              v-model:file-list="importForm.file"
              name="file"
              :multiple="false"
              action="#"
              :remove="handleRemove"
              :beforeUpload="beforeUploadPayment"
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              选择文件
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import {onMounted, reactive, ref, toRefs, computed} from 'vue'
import {selectMerchant} from "../../../api";
import {
  fetchPayLoanList,
  exportLoanDetails,
  payLoanStatus,
  payBatchPushOrder,
  payPushOrder,
  payLookVoucher,
  exportPaymentExcel,
  paymentProductNameList,
  paymentOperationList,
  importPaymentExcel
} from "../../../api/transaction";
import i18n from "../../../locale";
import {formatMoney} from "../../../utils";
import {export_json_to_excel} from "../../../utils/exportExcel";
import {message, Modal} from "ant-design-vue";
import bankDetails from '../../../components/bankDetails/index'
import {ExportOutlined, ImportOutlined, UploadOutlined} from "@ant-design/icons-vue"

const $t = i18n.global.t
const statusList = [
  {value: -1, label: $t('打款退回')},
  {value: 0, label: $t('待打款')},
  {value: 1, label: $t('处理中')},
  {value: 2, label: $t('打款成功')},
  {value: 3, label: $t('打款失败')},
]
const tableColumn = [
  {
    title: $t('交易流水'),
    dataIndex: 'transactionId',
    width: 150,
    align: 'center',
  },
  {title: $t('平台订单号'), dataIndex: 'platOrderId', width: 200, align: 'center'},
  {title: $t('商户订单号'), dataIndex: 'orderId', width: 150, align: 'center'},
  {title: $t('APP名称'), dataIndex: 'productName', width: 100, align: 'center'},
  {title: $t('应用ID'), dataIndex: 'appId', width: 100, align: 'center'},
  {title: $t('客户姓名'), dataIndex: 'userName', width: 100, align: 'center'},
  {title: $t('身份证号码'), dataIndex: 'idCard', width: 150, align: 'center'},
  {title: $t('收款账号'), dataIndex: 'bankNo', width: 150, align: 'center'},
  {title: 'cci', dataIndex: 'cci', width: 100, align: 'center'},
  {title: $t('银行名称'), dataIndex: 'bankName', width: 100, align: 'center'},
  {
    title: $t('打款金额'), dataIndex: 'payAmount', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('手续费'), dataIndex: 'fee', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {
    title: $t('手续费扣除方式'), dataIndex: 'deductionType', width: 100, align: 'center', customRender: ({text}) => {
      return text === 1 ? $t('手续费另计') : $t('从金额中扣除')
    }
  },
  {
    title: $t('到账金额'), dataIndex: 'receivedAmount', width: 100, align: 'center', customRender: ({text}) => {
      return formatMoney(text)
    }
  },
  {title: $t('创建时间'), dataIndex: 'createTime', width: 150, align: 'center'},
  {title: $t('完成时间'), dataIndex: 'endTime', width: 150, align: 'center'},
  {title: $t('订单负责人'), dataIndex: 'adminUserName', width: 100, align: 'center'},
  {title: $t('打款操作人'), dataIndex: 'operatorName', width: 100, align: 'center'},
  {
    title: $t('状态'), dataIndex: 'status', width: 100, align: 'center', customRender: ({text}) => {
      return text === 1 ? $t('处理中') : statusList.find(item => item.value === text).label
    }
  },
  {title: $t('标识符'), dataIndex: 'identifier', width: 150, align: 'center'},
  {title: $t('描述'), dataIndex: 'statusDesc', width: 200, align: 'center',},
  {title: $t('操作'), width: 150, fixed: 'right', align: 'center', slots: {customRender: 'handle'}},
]
export default {
  name: "LoanDetail",
  components: {
    bankDetails,
    ExportOutlined,
    ImportOutlined,
    UploadOutlined
  },
  setup() {
    const importRefForm = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      tableLoading: false,
      merchantList: [],
      statusVisible: false,
      statusForm: {},
      exportLoading: false,
      voucherVisible: false,
      selectedRowKeys: [],
      voucherUrl: '',
      exportPaymentLoading: false,
      importPaymentVisible: false,
      productNameList: [],
      importForm: {
        file: [],
        productName: null,
        mchId: null
      },
      importProductList:[],
      operationList:[]
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + $t('条'),
      onChange: (value) => {
        state.page.pageNum = value
        methods.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        methods.getTableData()
      }
    }))
    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: (value) => {
        state.selectedRowKeys = value
      }
    }))
    const methods = {
      async getTableData() {
        state.tableLoading = true
        const [createTimeStart, createTimeEnd] = state.page.createTime || []
        const [endTimeStart, endTimeEnd] = state.page.resolveTime || []
        const params = {
          ...state.page,
          createTimeStart, createTimeEnd, endTimeStart, endTimeEnd,
          createTime: undefined,
          resolveTime: undefined
        }
        const res = await fetchPayLoanList(params)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
          state.tableLoading = false
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        methods.getTableData()
      },
      batchPush() {
        if (state.selectedRowKeys.length <= 0) return message.error($t('请勾选订单'))
        Modal.confirm({
          title: $t('确认推送') + '?',
          async onOk() {
            const res = await payBatchPushOrder(state.selectedRowKeys)
            if (res.code === 200) {
              message.success($t('操作成功'))
              methods.getTableData()
              state.selectedRowKeys = []
            }
          },
        });
      },
      push({platOrderId}) {
        Modal.confirm({
          title: $t('确认推送') + '?',
          async onOk() {
            const res = await payPushOrder({platOrderId})
            if (res.code === 200) {
              message.success($t('操作成功'))
              methods.getTableData()

            }
          },
        });
      },
      async lookVoucher({platOrderId}) {
        state.voucherUrl = ""
        const res = await payLookVoucher({platOrderId})
        if (res.code === 200) {
          state.voucherVisible = true
          state.voucherUrl = res.data || ''
        }
      },
      changeStatusConfirm() {
        Modal.confirm({
          title: $t('确认进行此操作') + '?',
          async onOk() {
            const {id, changeStatus} = state.statusForm
            const res = await payLoanStatus({id, status: changeStatus})
            if (res.code === 200) {
              state.statusVisible = false
              message.success($t('操作成功'))
              methods.getTableData()
            }
          },
        });
      },
      async exportExcel() {
        state.exportLoading = true
        const [createTimeStart, createTimeEnd] = state.page.createTime || []
        const [endTimeStart, endTimeEnd] = state.page.resolveTime || []
        const params = {
          ...state.page,
          createTimeStart, createTimeEnd, endTimeStart, endTimeEnd,
          createTime: undefined,
          resolveTime: undefined
        }
        const res = await exportLoanDetails(params)
        if (res.code === 200) {
          const headerData = tableColumn.filter(item => !item.isHide && item.title !== $t('操作'))
          const column = headerData.map(item => item.title)
          const filterVal = headerData.map(item => item.dataIndex)
          const list = [...res.data].map((item) => {
            item.status = item.status === 1 ? $t('处理中') : statusList.find(_ => _.value === item.status).label
            return item;
          }).map((v) => filterVal.map((j) => v[j]));
          const fileName = $t("打款明细");
          export_json_to_excel({
            header: column,
            data: list,
            filename: fileName,
          });
          state.exportLoading = false
        } else {
          state.exportLoading = false
        }
      },
      // 导出打款
      exportPayment() {
        Modal.confirm({
          title: $t('确认进行此操作') + '?',
          async onOk() {
            const [createTimeStart, createTimeEnd] = state.page.createTime || []
            const [endTimeStart, endTimeEnd] = state.page.resolveTime || []
            const params = {
              ...state.page,
              createTimeStart, createTimeEnd, endTimeStart, endTimeEnd,
              createTime: undefined,
              resolveTime: undefined
            }
            state.exportPaymentLoading = true
            const res = await exportPaymentExcel(params)
            if (res) {
              const a = document.createElement("a")
              const blob = new Blob([res])
              a.download = '打款数据.xlsx'
              a.href = window.URL.createObjectURL(blob)
              a.click()
            }
            state.exportPaymentLoading = false
          },
        });
      },
      importPayment() {
        paymentProductNameList({}).then(res => {
          state.importProductList = res.data
        })
        state.importPaymentVisible = true
      },
      beforeUploadPayment(file) {
        let fileName = file.name.split('.')[1]
        if (['xlsx', 'xls', 'xltx', 'xlt', 'xlsm', 'xlsb', 'xltm', 'csv'].indexOf(fileName) === -1) {
          message.error($t('文件格式错误'))
          return Promise.reject()
        }
        if (state.importForm.file.length > 0) {
          message.error($t('一次只能上传单个文件'))
          return Promise.reject()
        }
        return false;
      },
      handleRemove() {
        state.importForm.file = []
      },
      // 导入回执提交
      importPaymentConfirm() {
        importRefForm.value.validate().then(async (v) => {
          if (v) {
            const formData = new FormData()
            formData.append('file', state.importForm.file[0])
            formData.append('productName', state.importForm.productName)
            formData.append('mchId', state.importForm.mchId)
            const res = await importPaymentExcel(formData)
            if (res.code === 200) {
              methods.getTableData()
              message.success($t('操作成功'))
              state.importPaymentVisible = false
            }
          }
        })
      },
      // 导入切换商户
      importChangeProductName(value) {
        paymentProductNameList({mchId:value}).then(res => {
          state.importProductList = res.data
        })
      },
      importClose() {
        importRefForm.value.resetFields()
      }
    }
    onMounted(() => {
      selectMerchant().then(res => {
        state.merchantList = res
      })
      paymentProductNameList({}).then(res => {
        state.productNameList = res.data
      })
      paymentOperationList().then(res => {
        state.operationList = res.data
      })
      methods.getTableData()
    })
    return {
      importRefForm,
      pagination,
      statusList,
      rowSelection,
      tableColumn,
      ...methods,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
